import React, { useState, useEffect } from 'react';
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom';
import { 
  SearchOutlined, 
  HomeOutlined, 
  FileOutlined, 
  InfoCircleOutlined, 
  SettingOutlined, 
  DownOutlined,
  BarChartOutlined,
  UserOutlined,
  LogoutOutlined,
  LoginOutlined,
  GlobalOutlined
} from '@ant-design/icons';
import { Input, Button, message, Dropdown, type MenuProps } from 'antd';
import './MainLayout.css';
import BackToTop from '../components/BackToTop';
import CurrentTime from '../components/CurrentTime';
import { getCurrentUserPermissions, hasMenuPermission } from '../utils/routePermission';
import logo from '../assets/images/logo.svg'

// 菜单配置数组
const menuConfig = [
  {
    key: 'home',
    label: '首页',
    icon: <HomeOutlined style={{ marginRight: '5px' }} />,
    path: '/'
  },
  {
    key: 'data-management',
    label: '数据管理',
    icon: <FileOutlined style={{ marginRight: '5px' }} />,
    path: '/data-management'
  },
  {
    key: 'data-search',
    label: '数据检索',
    icon: <SearchOutlined style={{ marginRight: '5px' }} />,
    path: '/data-search'
  },

  {
    key: 'operation-management',
    label: '运行管理',
    icon: <SettingOutlined style={{ marginRight: '5px' }} />,
    path: '/type-config'
  },
  {
    key: 'user-management',
    label: '用户管理',
    icon: <UserOutlined style={{ marginRight: '5px' }} />,
    path: '/user-management'
  }
];

const MainLayout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState('');
  const [user, setUser] = useState<any>(null);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [visibleMenus, setVisibleMenus] = useState(menuConfig);

  // 检查用户登录状态和权限
  useEffect(() => {
    const token = localStorage.getItem('token');
    const userInfo = localStorage.getItem('user');
    
    if (token && userInfo) {
      try {
        const parsedUser = JSON.parse(userInfo);
        setUser(parsedUser);
        setIsLoggedIn(true);
        
        // 根据用户权限过滤菜单
        console.log('=== 菜单权限检查开始 ===');
        console.log('用户原始信息:', parsedUser);
        console.log('用户level值:', parsedUser.level);
        console.log('用户level类型:', typeof parsedUser.level);
        console.log('level === 1 判断结果:', parsedUser.level === 1);
        console.log('level == 1 判断结果:', parsedUser.level == 1);
        console.log('level === "1" 判断结果:', parsedUser.level === "1");
        
        // level=1的管理员直接显示所有菜单，无需检查user_perm
        if (parsedUser.level == 1 || parsedUser.level === "1") {
          console.log('管理员用户(level=1)，显示所有菜单');
          console.log('所有菜单配置:', menuConfig);
          setVisibleMenus(menuConfig);
        } else {
          console.log('非管理员用户，进行权限过滤');
          // 其他用户需要根据权限过滤菜单
          const userPermissions = getCurrentUserPermissions();
          console.log('用户权限信息:', userPermissions);
          
          if (userPermissions) {
            const filteredMenus = menuConfig.filter(menu => {
              const hasAccess = hasMenuPermission(menu.key, userPermissions);
              console.log(`菜单 ${menu.key} 权限检查:`, hasAccess);
              return hasAccess;
            });
            console.log('过滤后的菜单:', filteredMenus);
            setVisibleMenus(filteredMenus);
          } else {
            console.warn('无法获取用户权限信息，只显示首页菜单');
            // 如果无法获取权限信息，显示基础菜单
            setVisibleMenus([menuConfig[0]]); // 只显示首页
          }
        }
        console.log('=== 菜单权限检查结束 ===');
      } catch (error) {
        console.error('解析用户信息失败:', error);
        // 清除无效的用户信息
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        setIsLoggedIn(false);
        setUser(null);
        setVisibleMenus([menuConfig[0]]); // 只显示首页
      }
    } else {
      setIsLoggedIn(false);
      setUser(null);
      setVisibleMenus([menuConfig[0]]); // 未登录时只显示首页
    }
  }, []);

  // 处理退出登录
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setIsLoggedIn(false);
    setUser(null);
    message.success('退出登录成功');
    navigate('/login');
  };

  // 处理跳转到登录页
  const handleGoToLogin = () => {
    navigate('/login');
  };

  // 用户下拉菜单配置
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout
    }
  ];

  // 渲染用户信息区域
  const renderUserInfo = () => {
    if (isLoggedIn && user) {
      return (
        <Dropdown 
          menu={{ items: userMenuItems }} 
          placement="bottomRight"
          trigger={['click']}
        >
          <Button 
            type="text" 
            className="user-info"
            style={{ 
              height: 'auto',
              padding: '6px 18px',
              border: 'none',
              background: 'linear-gradient(90deg, #e3f0ff 0%, #f7fbff 100%)',
              color: '#1765ad',
              borderRadius: '18px',
              boxShadow: '0 2px 8px rgba(30, 87, 153, 0.06)',
              cursor: 'pointer'
            }}
          >
            <UserOutlined style={{ marginRight: '8px' }} />
            用户: {user.user || user.name || 'P001'}
            <DownOutlined style={{ marginLeft: '8px', fontSize: '12px' }} />
          </Button>
        </Dropdown>
      );
    } else {
      return (
        <Button 
          type="text" 
          className="user-info"
          onClick={handleGoToLogin}
          style={{ 
            height: 'auto',
            padding: '6px 18px',
            border: 'none',
            background: 'linear-gradient(90deg, #e3f0ff 0%, #f7fbff 100%)',
            color: '#1765ad',
            borderRadius: '18px',
            boxShadow: '0 2px 8px rgba(30, 87, 153, 0.06)',
            cursor: 'pointer'
          }}
        >
          <LoginOutlined style={{ marginRight: '8px' }} />
          点击登录
        </Button>
      );
    }
  };

  return (
    <div className="layout-container">
      <header className="header">
        <div className="header-top">
          <div className="header-left">
            <div className="logo"><img src={logo} /></div>
          </div>
          <div className="header-center">
            <div className="nav-container">
              <div className="menu-container">
                {visibleMenus.map(menu => (
                  <div className="dropdown-menu" key={menu.key}>
                    <Link
                      to={menu.path}
                      className={
                        location.pathname === menu.path ? 'nav-item active' : 'nav-item'
                      }
                    >
                      {menu.icon}
                      {menu.label}
                    </Link>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div className="header-right">
            {/*<span className="user-info">用户:P001</span>*/}
            <CurrentTime />
            <Input.Search
              hidden
              placeholder="请输入检索数据关键字"
              allowClear
              enterButton
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              onSearch={value => {
                setSearchQuery(value);
                // 实现搜索逻辑
                console.log('搜索:', value);
              }}
              style={{ width: 240, marginLeft: 16 }}
            />
            {renderUserInfo()}
          </div>
        </div>
      </header>
      
      <main className="main-content">
        <Outlet />
      </main>
      
      <footer className="footer">
        <p>京公网安备1101080021345号 | 京ICP备09070537号</p>
      </footer>
      <BackToTop />
    </div>
  );
};

export default MainLayout; 